import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author huchuc@vip.qq.com
 * @date: 2019/10/12
 */
public class TestJavaUtilHashMap {
    /**
     * 100万
     */
    final static int TEST_COUNT = 1000000;


    public static void main(String[] args) {
        testManyThread();
    }

    /**
     * 单线程多次运行测试
     */
    public static void testOneThread() {
        for (int i = 0; i < 10; i++) {
            java.util.HashMap<String, String> stringHashMap = new java.util.HashMap<>();
            long start = System.currentTimeMillis();
            for (int x = 0; x < TEST_COUNT; x++) {
                stringHashMap.put("小美" + x, x + "岁的小美");
            }
            System.out.println("单线程第[" + (i + 1) + "]次运行 耗时 " + (System.currentTimeMillis() - start) + " ms");
        }
    }

    /**
     * 多线程测试
     */
    public static void testManyThread() {
        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            threads.add(new Thread(new MyHasshMapThread(i, TEST_COUNT)));
        }
        Iterator<Thread> iterator = threads.iterator();
        while (iterator.hasNext()) {
            iterator.next().start();
        }
    }

    private static class MyHasshMapThread implements Runnable {

        private int threadIndex;
        private int count;

        public MyHasshMapThread(int threadIndex, int count) {
            this.threadIndex = threadIndex;
            this.count = count;
        }

        @Override
        public void run() {
            java.util.HashMap<String, String> stringHashMap = new java.util.HashMap<>();
            long start = System.currentTimeMillis();
            for (int i = 0; i < this.count; i++) {
                stringHashMap.put("小美" + i, i + "岁的小美");
            }
            System.out.println("JDK HashMap线程[" + threadIndex + "]   耗时 " + (System.currentTimeMillis() - start) + " ms");
        }
    }
}
